package services

import (
	"go-mvc-ecommerce/models"

	"gorm.io/gorm"
)

type ProductService struct {
	db *gorm.DB
}

func NewProductService(db *gorm.DB) *ProductService {
	return &ProductService{db: db}
}

// 创建商品
func (s *ProductService) CreateProduct(name string, price float64, stock int) (*models.Product, error) {
	product := &models.Product{
		Name:  name,
		Price: price,
		Stock: stock,
	}

	result := s.db.Create(product)
	if result.Error != nil {
		return nil, result.Error
	}

	return product, nil
}

// 获取所有商品
func (s *ProductService) GetAllProducts() ([]models.Product, error) {
	var products []models.Product
	result := s.db.Find(&products)
	if result.Error != nil {
		return nil, result.Error
	}
	return products, nil
}

// 获取单个商品
func (s *ProductService) GetProductByID(productID uint) (*models.Product, error) {
	var product models.Product
	result := s.db.First(&product, productID)
	if result.Error != nil {
		return nil, result.Error
	}
	return &product, nil
}

// 更新商品库存
func (s *ProductService) UpdateProductStock(productID uint, newStock int) error {
	result := s.db.Model(&models.Product{}).Where("id = ?", productID).Update("stock", newStock)
	return result.Error
}
